#!/bin/bash

g_Sh_Src_Path="$1"
g_Sh_Pro_Name="$2"
g_Sh_Chip_Name="$3"
g_Sh_Show_Pro="$5"
g_Sh_Strip_Tool=""

g_Sh_ProDef_txt=$g_Sh_Src_Path/Config/CMakeLists.txt

# 检测芯片平台的strip工具 #
Sh_Func_Check_Tool_Strip()
{
    if [ "$g_Sh_Chip_Name" = "AnyKaEV300L" ];then
        g_Sh_Strip_Tool=arm-anycloud-linux-uclibcgnueabi-strip
    elif [ "$g_Sh_Chip_Name" = "IngenicT41" ];then
        g_Sh_Strip_Tool=mips-linux-uclibc-strip
    else
        echo -e "\033[31;47mNo such Chip $g_Sh_Chip_Name\033[0m"
        exit 0
    fi

    echo "$g_Sh_Strip_Tool" > $g_Sh_Src_Path/ToolStrip.txt
    return 1
}

Sh_Func_Show_Pro_Name()
{
    if [ -d "$g_Sh_Src_Path/Config/Project_Name" ];then
        rm $g_Sh_Src_Path/Config/Project_Name/*
    else
        mkdir -p $g_Sh_Src_Path/Config/Project_Name
    fi

    while read line
    do
        touch $g_Sh_Src_Path/Config/Project_Name/$line
    done < list.txt

    ls $g_Sh_Src_Path/Config/Project_Name/
}

# 选择编译项目 #
Sh_Func_List_Pro()
{
    cat $g_Sh_ProDef_txt | awk -F 'set\\(' '{ print $2 }' |awk -F ' ' '{ print $1 }' > list.txt
    sed -i "s/\<1\>/0/g" $g_Sh_ProDef_txt

    if [ "$g_Sh_Pro_Name" = "" ] || [ "$g_Sh_Chip_Name" = "" ] ; then
        echo -e "\033[30;47mbuild [project] [chip] [IOT]:\033[0m"
        echo -e "\033[33m[project]"
        Sh_Func_Show_Pro_Name
        echo -e "\033[0m"
        echo -e "\033[36m[chip]"
        ls $g_Sh_Src_Path/IPC_Code/ChipSdk --ignore=*.txt --ignore=*.h --ignore=*.c --ignore=GpioCtrl \
        --ignore=PtzMotor --ignore=PwmCode --ignore=WatchDog
        echo -e "\033[0m"
        rm list.txt
        exit 0
    else
        pro_val=`cat $g_Sh_ProDef_txt | grep -w $g_Sh_Pro_Name`
        if [ "$pro_val" = "" ];then
            echo -e "\033[31mNo such $g_Sh_Pro_Name, please check:"
            Sh_Func_Show_Pro_Name
            echo -e "\033[0m"
            rm list.txt
            exit 0
        fi
    fi
}

# 自动设置编译项目 #
Sh_Func_Set_Pro()
{
    if [ -e "./list.txt" ];then
        rm list.txt
    fi

    if [ "$g_Sh_Pro_Name" != "" ];then
        pro_src=`cat $g_Sh_ProDef_txt | grep -w $g_Sh_Pro_Name |awk -F ')' '{ print $1 }'`
        pro_replace=`cat $g_Sh_ProDef_txt | grep -w $g_Sh_Pro_Name |awk -F ')' '{ print $1 }' |sed "s/\<0\>/1/g"`
        sed -i "s/$pro_src/$pro_replace/g" $g_Sh_ProDef_txt
    fi
}

# 编译类型打印 #
Sh_Func_Cmake_Prinf()
{
    echo -e "\033[31;47mProject=$g_Sh_Pro_Name,Chip=$g_Sh_Chip_Name\033[0m"
    echo -e "\033[31;47m`cat $g_Sh_ProDef_txt | grep -w $g_Sh_Pro_Name`\033[0m"
}

if [ "$g_Sh_Show_Pro" != "" ];then
    Sh_Func_Cmake_Prinf
    exit
fi

Sh_Func_List_Pro
Sh_Func_Set_Pro
Sh_Func_Check_Tool_Strip
